package com.woniu.common.api.jwt;

import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUtils {

    /**
     * 秘钥库的密码 123456
     */
    private String keyStoreSecurity;

    /**
     * 秘钥的密码 123456
     */
    private String keySecurity;

    /**
     * 秘钥库的别名  jwt
     */
    private String alias;

    /**
     * 秘钥文件的路径 jwt.jks
     */
    private String filePath;

    /**
     * 获取秘钥对
     *
     * @return
     */
    public KeyPair getKeyPair() {
        KeyStoreKeyFactory factory =
                new KeyStoreKeyFactory(new ClassPathResource(filePath), keyStoreSecurity.toCharArray());
        return factory.getKeyPair(alias, keySecurity.toCharArray());
    }

    /**
     * 获取签名
     *
     * @return
     */
    public JWTSigner jwtSigner() {
        return JWTSignerUtil.createSigner("RSA", getKeyPair());
    }

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String createToken(Map<String, Object> payload) {
        return JWTUtil.createToken(payload, jwtSigner());
    }

    /**
     * 解析token
     *
     * @param token
     * @param claimName
     * @return
     */
    public Object getClaim(String token, String claimName) {
        return JWTUtil.parseToken(token).getPayload().getClaim(claimName);
    }
    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public boolean verifyToken(String token) {
        return JWTUtil.verify(token, jwtSigner());
    }

}
